<template>
  <div>
    <el-dialog
      :title="type==='add'?'新增区域':'编辑区域'"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="close"
    >
      <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
          <el-form-item label="区域名称：" prop="name">
            <el-input
              v-model.trim="form.name"
              placeholder="请输入区域名称"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" round @click="hide">取 消</el-button>
        <el-button size="small" round type="primary" :disabled="loading" @click="handleSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveTableArea } from '../../../api/table'
export default {
  data() {
    /**
       * 表单校验方法相关
       */

    return {
      /**
         * 表单校验字段相关
         */
      rules: {
        // 名称
        name: [
          {
            required: true,
            message: '请输入区域名称',
            trigger: ['blur', 'change']
          }
        ]
      },
      resolve: null,
      reject: null,
      // 状态
      loading: false,
      dialogVisible: null,
      // 数据
      type: 'add',
      form: {
        name: '',
        shopId: ''
      }
    }
  },
  methods: {
    open(type, shopId, params = '') {
      if (type === 'add') {
        this.form.shopId = shopId
      } else {
        this.form = Object.assign({}, params)
      }
      this.type = type
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },
    show() {
      this.dialogVisible = true
    },
    close() {
      this.form = {
        name: '',
        shopId: ''
      }
      this.loading = false
      this.$refs.form.resetFields()
    },
    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    // 保存
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          saveTableArea(this.form)
            .then(res => {
              this.$notify({
                title: '成功',
                message: '保存区域成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.resolve()
              this.hide()
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
